package com.l.web.master.system.dictionary;

import com.l.web.common.sequence.SequenceService;
import org.l.qiao.Cluster;
import org.l.qiao.builder.Field;
import org.l.qiao.builder.Query;
import org.l.qiao.builder.Sort;
import org.l.qiao.builder.Update;
import org.l.qiao.web.KeyUpdate;
import com.l.web.common.ResponseCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class DictionaryService {
    @Autowired
    private DictionaryDao dictionaryDao;

    @Autowired
    private SequenceService sequenceService;

    public List getList(Sort sort) {
        List dictionarys = dictionaryDao.find(null, null, sort);
        return dictionarys;
    }

    public Cluster detail(int id) {
        Cluster dictionary = dictionaryDao.findById(id);
        return dictionary;
    }

    public int save(Dictionary dictionary) {
        long id = sequenceService.dictionaryNext();
        dictionary.put(Dictionary.ID, id);
        dictionary.put(Dictionary.CREATED, new Date());
        return dictionaryDao.insert(dictionary);
    }

    public long update(KeyUpdate keyUpdate) {
        return dictionaryDao.update(keyUpdate);
    }

    public int remove(List<String> ids) {
        List<Integer> list = new ArrayList<>();

        for (String id : ids) {
            list.add(Integer.parseInt(id));
        }

        Query query = new Query();
        query.in(Dictionary.ID, list);
        dictionaryDao.remove(query);
        return ResponseCode.FINISH;
    }

    /**
     * 设置字典项
     *
     * @param id
     * @param key
     * @param value
     * @return
     */
    public long updateKey(int id, String key, String value) {
        Query query = new Query();
        query.eq(Dictionary.ID, id);

        Update update = new Update();
        update.set(Dictionary.KEY + '.' + key, value);
        return dictionaryDao.updateOne(query, update);
    }

    public long removeKey(int id, String key) {
        Query query = new Query();
        query.eq(Dictionary.ID, id);

        Update update = new Update();
        update.unset(Dictionary.KEY + '.' + key);
        return dictionaryDao.updateOne(query, update);
    }

    public Map<String, Map> dictionarys(int... ids) {
        List<Integer> list = new ArrayList();

        for (int id : ids) {
            list.add(id);
        }

        Query query = new Query();
        query.in(Dictionary.ID, list);

        Field field = new Field(Dictionary.ID, Dictionary.KEY);
        List<Cluster> dicts = dictionaryDao.find(query, field, null);
        Map<String, Map> mapKey = new HashMap<>();

        for (Cluster dict : dicts) {
            mapKey.put(dict.getString(Dictionary.ID), dict.getMap(Dictionary.KEY));
        }

        return mapKey;
    }

    public Cluster dictionary(int id) {
        return dictionaryDao.findById(id);
    }
}
